import { FC, useRef, useState } from "react"
import Taro from '@tarojs/taro'
import truck from '../../resource/truck.png'
import uncheck from '../../resource/uncheck.png'
import checked from '../../resource/checked.png'
import style from './style.less'

const Login: FC = () => {
  const [check, setCheck] = useState(false)

  // 用于防止重复弹窗
  const flag = useRef(false)

  const login = () => {
    if (!check) {
      Taro.showToast({
        title: '请勾选自动注册',
        icon: 'none',
        duration: 1500
      })
      return
    }
    if (flag.current) {
      return
    }
    flag.current = true
    Taro.getUserProfile({
      desc: '用于完善会员资料',
      success: () => {
        flag.current = false
        Taro.login({
          success: (res) => {
            Taro.showLoading({
              title: '加载中',
            })
            Taro.request({
              url: 'http://10.190.84.29:9527/fta-usercenter/auth/login/applets',
              method: 'POST',
              data: JSON.stringify({ code: res.code }),
              success: (data) => {
                Taro.setStorageSync('token', data.data.data.token)
                Taro.setStorageSync('auth', data.data.data.isAuth)
                Taro.setStorageSync('vip', data.data.data.isMembership)
                Taro.hideLoading()
                if (Taro.getStorageSync('auth')) {
                  Taro.setStorageSync('refresh', true)
                  Taro.navigateBack({ delta: 1 })
                } else {
                  Taro.redirectTo({ url: '/packageA/authentication/index' })
                }
              },
              fail: () => {
                Taro.hideLoading()
              }
            })
          }
        })
      },
      fail: () => {
        flag.current = false
      }
    })
  }

  return (
    <div className={style.root}>
      <div className="title">
        <img src={truck} alt="" />
        Man Man Yun
      </div>
      <div className="desc">满满运只为让您用的放心，选择满满，选择成功</div>
      <div className="login" onClick={login}>同意协议并使用微信账号一键登录</div>
      <div className="auto" onClick={() => { setCheck(!check) }}>
        {check ? <img src={checked} alt="" /> : <img src={uncheck} alt="" />}
        首次登录自动注册账号
      </div>
      <div className="agreement">且已阅读并同意<i>《用户服务协议》</i><i>《隐私政策》</i><i>《用户授权协议》</i></div>
    </div>
  )
}

export default Login